package com.nacrtstudio.webgiftshop.components;

import java.io.IOException;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.apache.tapestry5.*;
import org.apache.tapestry5.annotations.*;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.*;
import org.apache.tapestry5.services.RequestGlobals;
import org.apache.tapestry5.services.Response;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.SymbolConstants;
import org.slf4j.Logger;
import org.tynamo.security.pages.Login;
import org.tynamo.security.services.PageService;
import org.tynamo.security.services.SecurityService;

import com.nacrtstudio.webgiftshop.facade.Controller;
import com.nacrtstudio.webgiftshop.model.shop.Address;
import com.nacrtstudio.webgiftshop.model.shop.Cart;
import com.nacrtstudio.webgiftshop.model.shop.CartItem;
import com.nacrtstudio.webgiftshop.model.shop.Category;
import com.nacrtstudio.webgiftshop.model.shop.User;
import com.nacrtstudio.webgiftshop.model.shop.beans.AddressBean;
import com.nacrtstudio.webgiftshop.model.shop.beans.CartBean;
import com.nacrtstudio.webgiftshop.model.shop.beans.UserBean;
import com.nacrtstudio.webgiftshop.pages.CategoryGifts;
import com.nacrtstudio.webgiftshop.pages.ShoppingCart;
import com.nacrtstudio.webgiftshop.pages.StatusPage;
import com.nacrtstudio.webgiftshop.util.shop.Country;
import com.nacrtstudio.webgiftshop.util.shop.Role;

/**
 * Layout component for pages of application webgiftshop.
 */
//@Import(stylesheet = "context:layout/layout.css")
@Import(stylesheet={
        "classpath:/com/trsvax/bootstrap/assets/bootstrap/css/bootstrap.css",
        "context:layout/style.css",
        "context:layout/bs-changes.css"
        },
library={
        "classpath:/com/trsvax/bootstrap/assets/bootstrap/js/bootstrap.js",
        "context:layout/js/scripts.js"
        }
)
public class Layout extends Login
{
    /**
     * The page title, for the <title> element and the <h1> element.
     */
    @Property
    @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
    private String title;

    @Property
    private String pageName;

    @Property
    @Parameter(defaultPrefix = BindingConstants.LITERAL)
    private String sidebarTitle;

    @Property
    @Parameter(defaultPrefix = BindingConstants.LITERAL)
    private Block sidebar;

    @Inject
    private ComponentResources resources;

    @Property
    @Inject
    @Symbol(SymbolConstants.APPLICATION_VERSION)
    private String appVersion;


    public String getClassForPageName()
    {
        return resources.getPageName().equalsIgnoreCase(pageName)
                ? "current_page_item"
                : null;
    }

    public String[] getPageNames()
    {
        return new String[]{"Index", "About", "Gifts", "Instructions", "Faq", "Contact"};
    }
    
    @Inject
    @Property
    private Controller controller;
    @Property
    private Category category;
    @InjectPage
    private CategoryGifts categoryGifts;
    @InjectPage
    private ShoppingCart cart;
    
    public String getSerbianPageNames(){
    	if (pageName == "Index") {
			return "Početna";
		} else if(pageName == "About"){
			return "O nama";
		} else if(pageName == "Gifts"){
			return "Pokloni";
		} else if(pageName == "Instructions"){
			return "Instrukcije";
		} else if(pageName == "Faq"){
			return "Pitanja";
		} else if(pageName == "Contact"){
			return "Kontakt";
		}
    	return pageName;
    }
    
    public User getUser(){
    	return controller.getLoggedUser();
    }
    
    @Inject
	private SecurityService securityService;
	
	void onActionFromLogout(){
		Subject currentUser = securityService.getSubject();
		currentUser.logout();
		controller.logout();
	}
	
	public int getItemsInCart(){
		try {
			int num = 0;
			if (controller.getLoggedSignal() && controller.getLoggedUser().getCart().getCartItems()!=null) {
				for (CartItem cartItem : controller.getLoggedUser().getCart().getCartItems()) {
					num = num + cartItem.getQty();
				}
				return num;
			}
		} catch (Exception e) {
			return 0;
		}
		return 0;
	}
	
	public List<Category> getAllGiftCategories() {
		return controller.getAllCategories();
	}
	
	Object onActionFromShow(Long id){
		categoryGifts.setCategory(controller.getCategory(id));
		return categoryGifts;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	@Inject
	private Logger logger;

	@Property
	private String jsecLogin;

	@Property
	private String jsecPassword;

	@Property
	private boolean jsecRememberMe;

	@Persist(PersistenceConstants.FLASH)
	private String loginMessage;

	@Inject
	private Response response;

	@Inject
	private RequestGlobals requestGlobals;



	@Inject
	private PageService pageService;
	
	
	@Persist
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Object onActionFromJsecLoginForm()
	{

		Subject currentUser = securityService.getSubject();

		if (currentUser == null)
		{
			throw new IllegalStateException("Subject can`t be null");
		}

		UsernamePasswordToken token = new UsernamePasswordToken(jsecLogin, jsecPassword);
		token.setRememberMe(jsecRememberMe);

		try
		{
			currentUser.login(token);
			controller.login(jsecLogin, jsecPassword);
		} catch (UnknownAccountException e)
		{
			loginMessage = "Account not exists";
			return null;
		} catch (IncorrectCredentialsException e)
		{
			loginMessage = "Wrong password";
			return null;
		} catch (LockedAccountException e)
		{
			loginMessage = "Account locked";
			return null;
		} catch (AuthenticationException e)
		{
			loginMessage = "Authentication Error";
			return null;
		}

		SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(requestGlobals.getHTTPServletRequest());

		// TODO: try using shiro's own WebUtils.redirectToSavedRequest
		if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase("GET"))
		{
			try
			{
				response.sendRedirect(savedRequest.getRequestUrl());
				return null;
			} catch (IOException e)
			{
				logger.warn("Can't redirect to saved request.");
				return pageService.getSuccessPage();
			}
		} else
		{
			return pageService.getSuccessPage();
		}

	}

	public String getLoginMessage()
	{
		if (hasLoginMessage())
		{
			return loginMessage;
		} else
		{
			return " ";
		}
	}

	public boolean hasLoginMessage()
	{
		return StringUtils.hasText(loginMessage);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	@InjectComponent
	private Form registrationForm;
	
	@InjectPage
	private StatusPage statusPage;
	
	@Property
	private String email;
	@Property
	private String username;
	@Property
	private String password;
	@Property
	private String rePassword;
	@Property
	private boolean acceptTAC;	
	@Log
	public Object onSubmitFromRegistrationForm(){
		try {
			if (acceptTAC) {
				if (controller.getUserByUsername(username)==null) {
					User newUser  = new UserBean();
					Subject currentUser = securityService.getSubject();
					newUser.getRoles().add(Role.enduser);
					if (controller.getAllUsers().size()==0) {
						newUser.getRoles().add(Role.admin);
					}
					if (password.equals(rePassword)) {
						Address address = new AddressBean();
						address.setCountry(Country.Serbia_and_Montenegro);
						newUser.setAddress(address);
						Cart cart = new CartBean();
						newUser.setCart(cart);
						newUser.seteMail(email);
						newUser.setUsername(username);
						newUser.setPassword(password);
						controller.updateUser(newUser);
					}
					statusPage.setMessage("Uspešno ste se registrovali!");
					controller.login(newUser.getUsername(), newUser.getPassword());
					UsernamePasswordToken token = new UsernamePasswordToken(newUser.getUsername(), newUser.getPassword());
					currentUser.login(token);
					return statusPage;
				}
				statusPage.setMessage("Vase korisnicko ime je zauzeto");
				return statusPage;
			}
		} catch (Exception e) {
			statusPage.setMessage("Šifre koje ste uneli se ne poklapaju. Pokušajte ponovo!");
			return statusPage;
		}
		statusPage.setMessage("Morate da prihvatite uslove koriscenja!");
		return statusPage;
	}
}
